import { View, Button, Text } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useState } from "react";
import "./index.less";

export default function Login() {
  const [isLoading, setIsLoading] = useState(false);

  const handleUserAuth = async () => {
    setIsLoading(true);
    try {
      const { userInfo } = await Taro.getUserProfile({
        desc: "获取您的个人信息用于登录",
        lang: "zh_CN",
      });

      // 显示确认弹窗
      const { confirm } = await Taro.showModal({
        title: "请确认您的信息",
        content: `昵称: ${userInfo.nickName}`,
        confirmText: "确认",
        cancelText: "取消",
      });

      if (confirm) {
        const { code } = await Taro.login();
        console.log("授权结果:", { code, userInfo });
        // 存储登录状态或用户凭证
        Taro.setStorageSync("userInfo", userInfo);
        // 登录成功处理...
        Taro.navigateTo({
          url: "/pages/home/index",
        });
      }
    } catch (error) {
      Taro.showToast({
        title: "授权失败: " + error.errMsg,
        icon: "none",
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <View className="page-container">
      <Button
        type="primary"
        onClick={handleUserAuth}
        loading={isLoading}
        disabled={isLoading}
      >
        微信授权登录
      </Button>
    </View>
  );
}
